package com.bitcarton.disso.core.helper;
import com.bitcarton.disso.core.config.Config;
import com.bitcarton.disso.core.utils.CookieUtil;
import com.bitcarton.disso.core.utils.JedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.Model;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
/**
 * @author wwd 2021-06-28 10:15:38
 * @apiNote SSO SsoLoginHelper
 */
public final class SsoLoginHelper {
    /**
     * Login
     */
    public static String login(HttpServletResponse response,
                               String redirectUrl,
                               String domains,
                               Integer maxAge,
                               String accountJson,
                               Model model) {
        //用户名密码逻辑验证在统一认证中心校验
        String token = UUID.randomUUID().toString();
        CookieUtil.setCookie(response, Config.SSO_TOKEN, token, maxAge, Config.COOKIE_PATH, true, domains);
        JedisUtil.setStringValue(token, accountJson,maxAge);
        model.addAttribute(Config.SSO_TOKEN, token);
        return "redirect:" + redirectUrl;
    }


    /**
     * 验证是否登录
     */
    public static Object checkLogin(String redirectUrl, HttpServletRequest request,HttpServletResponse response,String loginUrl, Model model) {
        String token = CookieUtil.getValue(request, Config.SSO_TOKEN);
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(Config.SSO_TOKEN);
            if (StringUtils.isBlank(token)) {
                //表示没有全局会话
                model.addAttribute("redirectUrl", redirectUrl);
                return loginUrl;
            }
            if (!JedisUtil.exists(token)){
                //表示没有全局会话
                model.addAttribute("redirectUrl", redirectUrl);
                CookieUtil.remove(request,response,Config.SSO_TOKEN);
                return loginUrl;
            }
            model.addAttribute(Config.SSO_TOKEN, token);
            if (StringUtils.isBlank(redirectUrl)){
                return "redirect:/index";
            }
            Map<String,String> map = new HashMap<>(1);
            map.put(Config.SSO_TOKEN,token);
            try {
                redirect(redirectUrl,map,response);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        if (!JedisUtil.exists(token)){
            //表示没有全局会话
            model.addAttribute("redirectUrl", redirectUrl);
            return loginUrl;
        }
        if (StringUtils.isBlank(redirectUrl)){
            return "redirect:/index";
        }
        Map<String,String> map = new HashMap<>(1);
        map.put(Config.SSO_TOKEN,token);
        try {
            redirect(redirectUrl,map,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {
        if (JedisUtil.exists(token)) {
            return true;
        }
        return false;
    }


    /**
     * logout
     *
     * @param req
     * @param resp
     */
    public static void logout(HttpServletRequest req, HttpServletResponse resp) {
        String token = CookieUtil.getValue(req, Config.SSO_TOKEN);
        if (StringUtils.isNotBlank(token)) {
            CookieUtil.remove(req, resp, Config.SSO_TOKEN);
            JedisUtil.del(token);
        }
    }


    public static void redirect(String url, Map<String,String> params, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println(" <HEAD><TITLE>sender</TITLE></HEAD>");
        out.println(" <BODY>");
        out.println("<form name=\"submitForm\" action=\""+url+"\" method=\"post\">");
        Iterator<String> it=params.keySet().iterator();
        while(it.hasNext()){
            String key=it.next();
            out.println("<input type=\"hidden\" name=\""+key+"\" value=\""+params.get(key)+"\"/>");
        }
        out.println("</from>");
        out.println("<script>window.document.submitForm.submit();</script>");
        out.println(" </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }


    public static String getUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies){
            for (Cookie cookie : cookies) {
                String value = cookie.getValue();
                boolean exists = JedisUtil.exists(value);
                if (exists){
                    return JedisUtil.getStringValue(value);
                }
            }
        }
        String token = request.getParameter("token");
        if (StringUtils.isNotBlank(token)){
            boolean exists = JedisUtil.exists(token);
            if (exists){
                return JedisUtil.getStringValue(token);
            }
        }
        return null;
    }



}
